import matplotlib.pyplot as plt  #导入库定义为plt
import random
from pylab import mpl  #设置中文字体
from operator import itemgetter  #itemgetter用来去dict中的key，省去了使用lambda函数
from itertools import groupby  #itertool还包含有其他很多函数，比如将多个list联合起来。。
from pprint import pprint

mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False

fileData = []
fp1 = open(
    "C:\WorkSpace\gitee\heiben_py\heiben_py\main\TestLogFile\cpu_usage_all.log"
)
for line in fp1.readlines():
    str_list = line.split()
    if str_list and len(
            str_list) > 10 and str_list[3] != '%usr' and str_list[2] != 'all':
        if str_list[0] != "Average:":
            fileData.append({"v1": str_list[0], "v2": float(str_list[3])})

grouper = itemgetter("v1")
result = []
for key, grp in groupby(sorted(fileData, key=grouper), grouper):
    temp_list = [item["v2"] for item in grp]
    result.append({"v1": key, "v2": sum(temp_list) / len(temp_list)})

#pprint(result)
#print([x['v1'] for x in result])
#x_data = ['2011', '2012', '2013', '2014', '2015', '2016', '2017']
#y_data = [58000, 60200, 63000, 71000, 84000, 90500, 107000]

plt.figure(figsize=(20, 8), dpi=100)  #20x8,清晰度为100
plt.xlabel("时间")
plt.ylabel("usr")
plt.plot([x['v1'] for x in result], [x['v2'] for x in result],
         color='red',
         linewidth=2.0,
         linestyle='--')
plt.grid(True, linestyle="--", alpha=1)
#plt.savefig("./test.png")
plt.show()

#x = range(60)  #时间范围
#y_shanghai = [random.uniform(13, 17) for i in x]  #随机获取上海温度
#y_beijing = [random.uniform(3, 7) for i in x]  #随机获取北京温度
#plt.figure(figsize=(20, 8), dpi=100)  #20x8,清晰度为100
#plt.plot(x, xdata)  #绘制折线图
#plt.plot(x, y_beijing, color="r", linestyle="--", label="北京")
#x_ticks_label = ["11点{}分".format(i) for i in x]
#y_ticks = range(max(ydata))
#plt.xticks(x[::5], x_ticks_label[::5])  #划分坐标刻度和定义标签刻度
#plt.yticks(y_ticks[::5])
#plt.grid(True, linestyle="--", alpha=1)
#plt.title("中午11-12点城市温度变化图", fontsize=20)
#plt.savefig("./test.png")
#plt.legend(loc="best")
#plt.show()